package concordia.comp6231.common;

import java.util.Properties;

public class ApplicationConfig {

	
	public static int PORT_LEADER_ELECTION_SERVICE_SEND = 9;
	public static int PORT_LEADER_ELECTION_SERVICE_LISTENER = 7;
	
	public static final String REPLICA_GROUP_NAME 				= "replica.groupName";
	public static final String REPLICA_PROCESS_ID 				= "replica.processId";
	public static final String REPLICA_STATE 					= "replica.state";
	public static final String REPLICA_BOX_OFFICE_ID 			= "replica.boxOfficeId";
	public static final String REPLICA_SHOWS_BASE_DIRECTORY 	= "replica.showsBaseDirectory";
	public static final String REPLICA_SERVER_PORT				= "replica.serverport";
	public static final String LEADERELECTION_SERVER_PORT		= "leaderelection.serverport";
	public static final String FAILUREDETECTION_SERVER_PORT		= "failerdetection.serverport";
	public static final String FAILUREDETECTION_HEARTBEAT_FREQ	= "failerdetection.heartbeat_freq";
	public static final String GROUPMEMBERSHIP_SERVER_PORT		= "groupmembership.serverport";
	public static final String CORBA_PARAMS						= "corba.params";
	public static final int FAILUREDETECTION_SERVER_PORT_SEND	=5001;
	public static final int FAILUREDETECTION_SERVER_PORT_RECEIVE	=5000;
	
	private static Properties replicaProperties;
	
	public static void loadConfig(Properties properties) {
		replicaProperties = properties;
		checkProperty(REPLICA_PROCESS_ID);
		checkProperty(REPLICA_GROUP_NAME);
		checkProperty(REPLICA_STATE);
		checkProperty(REPLICA_BOX_OFFICE_ID);
		checkProperty(REPLICA_SERVER_PORT);
		checkProperty(LEADERELECTION_SERVER_PORT);
		checkProperty(FAILUREDETECTION_SERVER_PORT);
		checkProperty(GROUPMEMBERSHIP_SERVER_PORT);
	}
	
	private static void checkProperty(String name) {
		if (!replicaProperties.containsKey(name)) {
			System.err.println("Key, " + name + ", is missing from configuration!");
		}
	}
	
	public static String get(String key) {
		return getAsString(key);
	}
	
	public static String getAsString(String key) {
		return replicaProperties.getProperty(key);
	}

	public static int getAsInt(String key) {
		int result = -1;
		try {
			result = Integer.parseInt(replicaProperties.getProperty(key));
		} catch (NumberFormatException e) {
			System.err.println("Invalid int value for key: " + key);
		}
		return result;
	}

}
